<template>
  <d2-container>
  <section class="vue-monitor">
    <el-row>
      <el-col :span="5" class="monitor-d monitor-tree-d">
        <el-scrollbar :style="'height:100%;width: 100%'">
          <area-tree @nodeChange="treeNodeChange"></area-tree>
        </el-scrollbar>
      </el-col>
      <el-col :span="19" class="monitor-d" style="padding-left:10px">
        <div>
          <el-form label-position="right" :model="dataForm" :inline="true">
            <el-form-item class="el-form-item--mini" label="分类能耗：">

              <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="small">
                <el-option
                  v-for="(item, index) in meterTypeList" :key="index"
                  :label="item.paramValue"
                  :value="item.paramKey">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="el-form-item--mini" label="日期: ">
              <el-select v-model="dataForm.dateType" @change="changeDateType" placeholder="请选择"  size="small" style="width: 80px;">
                <el-option
                  v-for="(item, index) in Config.searchMaxDate" :key="index"
                  :label="item.label"
                  :value="item.date">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="el-form-item--mini" label="时间: ">
                <el-date-picker
                  v-model="dataForm.date"
                  placeholder="时间"
                  style="width: 200px;"
                  class="filter-item"
                  size="small"
                  :picker-options="pickerOptions"
                  :type="dataForm.dateType"
                  suffix-icon="el-icon-date"
                  clearable
                >
                </el-date-picker>
            </el-form-item>

            <el-form-item class="el-form-item--mini">
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="getPowerDataList"
              >查询</el-button>
              <!--<el-button-->
                <!--class="filter-item"-->
                <!--type="primary"-->
                <!--icon="el-icon-download"-->
                <!--size="small"-->
                <!--@click="exoprtData"-->
              <!--&gt;导出</el-button>-->
            </el-form-item>
          </el-form>
        </div>
        <div class="" style="margin-bottom: 10px">
          <div id="manage-bar" style="height:250px;" class="" />
        </div>
        <div>
          <el-table
            :data="meterdataList"
            border
            v-loading="dataListLoading"
            style="width: 100%;overflow:visible;"
          >
            <el-table-column
              prop="date"
              header-align="center"
              align="center"
              label="本期时间"
            ></el-table-column>
            <el-table-column
              prop="currentValue"
              header-align="center"
              align="center"
              :label="'本期能耗('+currentUnit+')'"
            >
            </el-table-column>
            <el-table-column
              prop="lastValue"
              header-align="center"
              align="center"
              :label="'同比能耗('+currentUnit+')'"
            >
            </el-table-column>
            <el-table-column
              prop="hb"
              header-align="center"
              align="center"
              label="同比(%)"
            >
              <template
                slot-scope="scope"
              >{{scope.row.tb}}
                <i v-if="scope.row.hb < 0" style="color: #099c44" class="el-icon-bottom"></i>
                <i v-if="scope.row.hb > 0" style="color: #df5a60" class="el-icon-top"></i></template>
            </el-table-column>
          </el-table>

        </div>
      </el-col>
    </el-row>
  </section>
  </d2-container>
</template>
<script>
import areaTree from './compont/area_tree_onceclick';
import * as Util from "@/utils";
import Config from "@/utils/config";
import * as echarts from 'echarts';
import { mapGetters } from 'vuex';
export default {
  /*
  * 环比分析
  **/
  data() {
    return {
      meterdataList:[],
      buildList: '',
      dataTypeDesc:'当日',
      lastDataTypeDesc:'昨日',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      Config:Config,
      meterTypeList:[],
      dataForm: {
        date: new Date(),
        dateType:'year',
        energyType:'',
        subEnergyType:'',//分项选择值
      },
      currentUnit:'',
      dataListLoading:false,
    }
  },
  components:{
    areaTree
  },
  methods: {
    formarDate(type, date) {
      return Util.dateFormat(Config.searchDate.find(item => item.date == type).format, date)
    },
    /**
     * 查询数据
     * */
    getPowerDataList() {
      if(this.dataForm.energyType ==''|| this.buildList == ''){
        return
      }

      this.dataListLoading = true;
      let datestr = this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date))
      let dateTypestr = Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc
      this.$api.okhttp({
        url:this.$http.adornUrl('/eas/yoyAnalysis/list'),
        method: "post",
        data: this.$http.adornParams(
          {
            buildingIds: [this.buildList],
            date: datestr,
            dateType: dateTypestr ,
            meterType: this.dataForm.energyType,
            customerId: this.$util.cookies.get("customer_id"),
            projectId:this.$util.cookies.get("cuuren_projectId")
          }
        )
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterdataList = data.data;
          this.drawBar(data)
        }
        this.dataListLoading = false;
      }).catch(()=>{
        this.dataListLoading = false;
      })
    },
    drawBar(dataList) {
      this.$nextTick(() => {
        const chart = echarts.init(document.querySelector('#manage-bar'))
        chart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['本期', '同期'],
            textStyle:{
              color: '#909399'
            }
          },
          grid: {
            left: '5%',
            right: '2%',
            top: '15%',
            bottom: '10%'
          },
          xAxis: {
            type: 'category',
            data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31].slice(0,dataList.thisYearList.length).map(i => i + (dataList.thisYearList.length >12?'日':'月')),
            axisLine: {
              lineStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#999'
              },
            },
          },
          yAxis: {
            name: this.currentUnit,
            type: 'value',
            nameTextStyle: {
              align: "right"
            },
            axisLine: {
              lineStyle: {
                color: this.activeSetting.name === 'd2' ? '#333' : '#999'
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#999']
              },
            },
          },
          series: [
            {
              name: '本期',
              data:dataList.thisYearList,
              type: 'bar',
              markPoint: {
                data: [
                  { type: 'max', name: 'Max' },
                  { type: 'min', name: 'Min' }
                ]
              }
            },
            {
              name: '同期',
              data:dataList.lastYearList,
              type: 'bar',
              markPoint: {
                data: [
                  { type: 'max', name: 'Max' },
                  { type: 'min', name: 'Min' }
                ]
              },
            }
          ]
        })
      })
    },

    getDateStr(){
      return  this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date))
    },
    exoprtData(){
      // 导出数据
      let headerDay=['区域名称','当日用能('+this.currentUnit+')','昨日用能('+this.currentUnit+')','增加值('+this.currentUnit+')','环比(%)'];
      let headerMonth=['区域名称','当月用能('+this.currentUnit+')','上月用能('+this.currentUnit+')','增加值('+this.currentUnit+')','环比(%)'];
      let props=['bName','currentValue','lastValue','addValue','hb']
      let fileName=`环比分析(${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue})${this.getDateStr()}统计`
      let header = headerDay
      if(this.dataForm.dateType==='month'){
        header = headerMonth
      }
      this.export2Excel(header,props,fileName,this.meterdataList);
    },
    export2Excel(tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const { export_json_to_excel } = require('@/utils/Export2Excel.js')
        const list = JSON.parse(JSON.stringify(dataList));
        // let sumVal = list.reduce(function (total, currentValue, currentIndex, arr) {
        //   return total + currentValue.val;
        // }, 0);
        // list.push({
        //   "buildingName":'合计',
        //   "val":sumVal
        // })
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    changeDateType() {
      if (this.dataForm.dateType === 'year') {
        this.dataTypeDesc = '当年'
        this.lastDataTypeDesc= '上年'

      } else if (this.dataForm.dateType === 'month') {
        this.dataTypeDesc = '当月'
        this.lastDataTypeDesc= '上月'
      }
    },
    treeNodeChange(data){
      this.buildList = data
      this.getPowerDataList()
    },
    queryStatic(type,paramValue,callback) {
      let params = {
        'code': type ,
        "customerId":this.$util.cookies.get('customer_id')
      }
      if(paramValue){
        Object.assign(params,{paramValue,paramValue});
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then((data) => {
        if(callback){
          callback(data);
        }
      });
    },

  },
  watch: {
    'dataForm.energyType':function(newV,oldV){
      this.currentUnit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
  },
  computed: {
    ...mapGetters('d2admin/theme', ['activeSetting']),
    containerHeight() {
      return Util.getClientHeight() - 163;
    },
    bottomChartHeight(){
      return Util.getClientHeight() - 298;
    }
  },
  created() {
    this.dataForm.dateType=Config.searchDate[1].date;
    this.$nextTick(()=>{
      this.queryStatic("METER_TYPE",null,data=>{
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.currentUnit = data.page[0].paramExt;
        } else {
          this.meterTypeList = []
        }
        this.getPowerDataList()
      });
    })
  }
}

</script>
<style scoped lang="scss">
  @import "../../assets/scss/_variables";
.vue-monitor {
  min-width: 900px;
}

.vue-monitor .el-row {
  width: 100%;
  display: flex;
  align-items: flex-start;
}
.vue-monitor .monitor-d{
  // box-shadow: 0px 0px 1px 1px #f7f6f6;
}
.vue-monitor .monitor-tree-d {
    /*position: absolute;*/
    height: 100%;
    top: 0;
    /*right: 0;*/
}




/*清除浮动代码*/

.clearfloat:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0
}

.clearfloat {
  zoom: 1
}


</style>
